package cn.legym.garp.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/**
 * @author chris
 * @Description 自定义过滤器
 * @date 2021/5/24  9:49
 */
@Component
@Slf4j
public class RequestFilter implements GlobalFilter, Ordered {

    /**
     * @Author chris
     * @Description 自定义过滤方法
     * @Date 9:59 2021/5/24
     * @Param [exchange, chain]
     * @return reactor.core.publisher.Mono<java.lang.Void>
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
//        System.out.println();
//        if (request.getMethod().equals(HttpMethod.POST)&&request.getPath().value().equals("/running/app/uploadRunningDetails")) {
//            Flux<DataBuffer> body = request.getBody();
//            body.subscribe(buffer -> {
//                byte[] bytes = new byte[buffer.readableByteCount()];
//                buffer.read(bytes);
////                DataBufferUtils.release(buffer);
//                buffer.readPosition(0);
//                try {
//                    String bodyString = new String(bytes, "utf-8");
//                    log.warn("body:{}$",bodyString);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//            });
//        }
        ServerHttpResponse response = exchange.getResponse();


        return chain.filter(exchange);
    }

    /**
     * @Author chris
     * @Description 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @Date 9:58 2021/5/24
     * @Param []
     * @return int
     **/
    @Override
    public int getOrder() {
        return 0;
    }
}
